import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from "./routes.js"
import NProgress from 'nprogress'
import { Message } from 'element-ui'
import until from '../until'
import store from '../store'
import { childrouts } from './homeroutes.js'



Vue.use(VueRouter)

const router = new VueRouter({
    routes
})

router.beforeEach(async (to, from, next) => {
    NProgress.start();
    if (to.meta.isCheckToken) {
        next();
        return;
    }
    if (!until.getToken()) {
        Message.error("请先完成登录")
        next({ name: 'login' })
        return;
    }
    // next();

    // if(store.state.menu.length==0){
    //     let menus= await store.dispatch("getMenu");
    //     for(let temp of menus){
    //         for(let menu of temp.children){
    //             let route=childrouts[menu.path]
    //             if(route==undefined){
    //                 continue;
    //             }
    //             router.addRoute("home",route)
    //         }
    //     }
    //     router.addRoute("home",childrouts.NoFind)
    // }

    // next({
    //     ...to
    // })
    const judgeMenus = store.state.menu && store.state.menu.length > 0;
    if (judgeMenus) {
        next();
    } else {
        try {
            let menus = await store.dispatch("getMenu");
            for (let one of menus) {
                for (let menu of one.children) {
                    let route = childrouts[menu.path]
                    if (route == undefined) {
                        continue
                    }
                    if(!route.meta){
                        route.meta={}
                    }
                    // route.meta.tip=["首页",one.authName,menu.authName]
                    route.meta.tip=[
                        // {name:"首页",      path:"home"},
                        {name:one.authName,path:one.path},
                        {name:menu.authName,path:menu.path},
                    ]
                    route.meta.id=menu.id+''
                    router.addRoute("home", route)

                }
            }
            router.addRoute("home", childrouts.nofind)
            next({ ...to })
        } catch (error) {
            // console.log(error)
            Message.error(error.Message)
        }
    }

})
router.afterEach(() => {
    NProgress.done();
})

export default router
